﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;


namespace WindowsGame1
{
    class ColorScale
    {   
        /// <summary>
        /// colors used for the color scale
        /// </summary>
        protected List<Color> _colors;
        /// <summary>
        /// position of color in colorscale
        /// </summary>
        protected List<double> _positionOfColors;


        #region constructor
        /// <summary>
        /// Constructor for ColorScale
        /// </summary>
        /// <param name="initialColors">List of colors to interpolate between</param>
        public ColorScale(List<Color> initialColors)
        {
            _colors = initialColors;
            //amount of colors in List
            int colorCount = _colors.Count;
            //calculate colorRange (between zero and one)
            float colorRange = 1 / (colorCount - 1);
            _positionOfColors = new List<double>();

            //add the position of colors(between zero and one) to a list -> color scale
            for (int i = 0; i < colorCount; i++)
            {
                _positionOfColors.Add(i/(colorCount - 1.0));
            }

        }
        #endregion

        /// <summary>
        /// calculates the color at a given position using linear interpolation
        /// </summary>
        /// <param name="position">position of value on the color scale</param>
        /// <returns>interpolated color</returns>
        public Color calculateColor(double position)
        {

            if (position < _positionOfColors.First())
            {
                return _colors.First();
            }
            //linear interpolation
            for (int i = 0; i < _positionOfColors.Count - 1; i++)
            {
                double prevPos = _positionOfColors.ElementAt(i);
                double nextPos = _positionOfColors.ElementAt(i + 1);
                if (position > prevPos && position < nextPos)
                {
                    Color prevColor = _colors.ElementAt(i);
                    Color nextColor = _colors.ElementAt(i + 1);

                    Vector3 f0 = new Vector3(prevColor.R, prevColor.G, prevColor.B);
                    Vector3 f1 = new Vector3(nextColor.R, nextColor.G, nextColor.B);

                    Vector3 newC = f0 + ((f1 - f0)/((float)nextPos - (float)prevPos)) * ((float)position - (float)prevPos) ;
                    
                    return new Color((int)newC.X, (int)newC.Y, (int)newC.Z, 1);
                               
                }

            }

            return _colors.Last(); 

        }
    }
}
